import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> list = new ArrayList<>();
        int len = nums.length;
        if(len < 4){
            return list;
        }
        //先排序数组
        Arrays.sort(nums);
        //处理有序数组
        int tmpNum1 = nums[0] + 1;
        for(int i = 0; i < len - 3; i++){
            //固定数1去重
            while(i < len - 3 && nums[i] == tmpNum1) i++;
            //判断后面的数是否有必要遍历
            if(nums[i] > target && nums[i] > 0) break;
            //第二个固定数
            int tmpNum2 = nums[i + 1] + 1;
            for(int j = i + 1; j < len - 2; j++){
                //固定数2去重
                while(j < len - 2 && nums[j] == tmpNum2) j++;
                //判断后面的数是否还有必要遍历
                if(nums[i] + nums[j] > target && nums[i] + nums[j] > 0) break;
                //双指针解决问题
                int left = j + 1;
                int right = len - 1;
                while(left < right){
                    if(left < right && sum(nums, i, j, left, right) > target) right--;
                    else if(left < right && sum(nums, i, j, left, right) < target) left++;
                    else{
                        List<Integer> group = new ArrayList<>();
                        group.add(nums[i]);
                        group.add(nums[j]);
                        group.add(nums[left]);
                        group.add(nums[right]);
                        list.add(group);
                        left++;
                        right--;
                        //双指针去重
                        while(left < right && nums[left] == nums[left - 1]) left++;
                        while(left < right && nums[right] == nums[right + 1]) right--;
                    }
                }
                tmpNum2 = nums[j];
            }
            tmpNum1 = nums[i];
        }
        return list;
    }
    //求4数之和
    private long sum(int[] nums, int i, int j, int k, int l){
        return nums[i] + nums[j] + nums[k] + nums[l];
    }
}
